#include <stdio.h>
#include <stdlib.h>

//定义链表节点
struct stu {
	int id;
	struct stu *next;
};
//别名
typedef struct stu STU;

//菜单
void Menu () {
	printf("   菜单 \n");
	printf("----------\n");
	printf("1)添加学号\n");
	printf("2)删除学号\n");
	printf("3)修改学号\n");
	printf("4)查询学号\n");
	printf("5)打印学号\n");
	printf("6)释放链表\n");
	printf("9)退出程序\n");
	printf("0)查看菜单\n");
	printf("----------\n");
}
void menu () {
		printf("0查看菜单\n");
}

//添加
//传入的实参是主函数中*head的地址,通过申请的内存地址赋值给*head(即*head = &new_stu)
void add_id (STU **head) {
	//申请内存空间,地址存入new_stu中
	STU *new_stu = (STU *)malloc(sizeof(STU));
	
	printf("输入id:\n");
	scanf("%d", &(new_stu->id));
	new_stu->next = NULL;
	
	//判断*head中的值是否为空
	if (*head == NULL) {
		//申请的空间的地址存入*head中
		*head = new_stu;
	} else {
		STU *p = *head;
		while (p->next != NULL) {
			p = p->next;
		}
		p->next = new_stu;
	}
}

//删除
//传入的实参是主函数中*head的地址,通过对head指向的地址进行操作
void del_id (STU **head) {
	printf("输入要删除的id:\n");
	int id = 0;
	scanf("%d", &id);
	
	int flag = 0;
	STU *p1 = *head, *p2 = NULL;
	while (p1 != NULL) {
		//判断删除的id在哪个节点
		if (p1->id == id) {
			printf("已删除id:%d\n", id);
			flag = 1;
			if (*head == p1) {
				*head = p1->next;
			} else {
				p2->next = p1->next;
			}
			free(p1);
			break;
		}
		p2 = p1;
		p1 = p1->next;
	}
	if (flag == 0) {
		printf("没有找到id:%d\n", id);
	}
}

//修改
void modify_id (STU *head) {
	printf("输入要修改的id:\n");
	int id = 0;
	scanf("%d", &id);
	
	int flag = 0;
	int i = 1;
	while (head != NULL) {
		if (head->id == id) {
			printf("已找到id:%d,请输入新的id:\n", id);
			scanf("%d", &(head->id));
			printf("成功将id:%d修改为%d\n", id, head->id);
			flag = 1;
		}
		head = head->next;
		i++;
	}
	if (flag == 0) {
		printf("没有找到id:%d\n", id);
	}
}

//查询
void search_id (STU *head) {
	printf("输入要查询的id:\n");
	int id = 0;
	scanf("%d", &id);
	
	int flag = 0;
	int i = 1;
	while (head != NULL) {
		if (head->id == id) {
			printf("已找到id:%d,在第%d个节点\n", id, i);
			flag = 1;
		}
		head = head->next;
		i++;
	}
	if (flag == 0) {
		printf("未找到id:%d\n", id);
	}
}

//打印全部
void prt_all_id (STU *head) {
	if (head == NULL) {
		printf("没有id:\n");
	}
	while (head != NULL) {
		printf("id:%d\n", head->id);
		head = head->next;
	}
}

//释放链表
void free_all (STU *head) {
	STU *temp = NULL;
	while (head != NULL) {
		temp = head;
		head = head->next;
		free(temp);
	}
}

int main () {
	//定义结构体指针,用于指向头节点
	STU *head = NULL;
	Menu();
	
	while (1) {
		printf("选择:\n");
		int option = 0;
		scanf("%d", &option);
		
		switch (option) {
		case 1:
			add_id(&head);
			break;
		case 2:
			del_id(&head);
			break;
		case 3:
			modify_id(head);
			break;
		case 4:
			search_id(head);
			break;
		case 5:
			prt_all_id(head);
			break;
		case 6:
			free_all(head);
			break;
		case 9:
			return 0;
			break;
		case 0:
			Menu();
			break;
		default:
			printf("重选:\n");
		}
	}
	return 0;
}